package intelligentCustomer.planning;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.model.StreamingResponseHandler;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.StreamingChatLanguageModel;
import dev.langchain4j.model.openai.OpenAiStreamingChatModel;
import dev.langchain4j.model.output.Response;

public class ReasonGenerator {

    public static String generate(OpenAiStreamingChatModel model, String prompt) {
         // 执行推理
        String reasoning;
        if (model instanceof ChatLanguageModel) {
            reasoning = ((ChatLanguageModel)model).generate(prompt);
        } else {
            // 使用流式API并收集结果
            StringBuilder result = new StringBuilder();
            CompletableFuture<String> future = new CompletableFuture<>();
            
            ((StreamingChatLanguageModel)model).generate(prompt, new StreamingResponseHandler<AiMessage>() {
                @Override
                public void onNext(String token) {
                    result.append(token);
                    System.out.print(token);
                }
                
                @Override
                public void onComplete(Response<AiMessage> response) {
                    future.complete(response.toString());
                }
                
                @Override
                public void onError(Throwable error) {
                    future.completeExceptionally(error);
                }
            });
            
            try {
                future.get(30, TimeUnit.SECONDS);
                reasoning = result.toString();
            } catch (Exception e) {
                reasoning = "推理过程中发生错误: " + e.getMessage();
            }

        }
        
        return reasoning;
    }
}
